//
//  VSTreeViewCell.m
//  ViewSeer
//
//  Created by LevinYan on 2017/3/21.
//  Copyright © 2017年 LevinYan. All rights reserved.
//

#import "VSTreeViewCell.h"


@implementation VSTreeViewCellModel

@end


@interface VSTreeViewCell()

@property (nonatomic, strong) UIImageView *expandedImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, assign) NSUInteger level;
@property (nonatomic, assign) BOOL expanded;
@end

@implementation VSTreeViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
   
    _expandedImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    _expandedImageView.image = [UIImage imageNamed:@"expanded"];
    _expanded = YES;
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    UIView *cellBg = [[UIView alloc] init];
    cellBg.backgroundColor = [UIColor colorWithRed:(76.0/255.0) green:(161.0/255.0) blue:(255.0/255.0) alpha:0.7]; // this RGB value for blue color
    cellBg.layer.masksToBounds = YES;
    self.selectedBackgroundView = cellBg;
    [self addSubview:_expandedImageView];
    [self addSubview:_nameLabel];
    
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    self.expandedImageView.center = CGPointMake(12 + 8*self.level, bounds.size.height/2);
    self.nameLabel.frame = CGRectMake(self.expandedImageView.frame.origin.x + self.expandedImageView.frame.size.width + 4, (bounds.size.height - 20)/2, bounds.size.width - 30, 20);
}

- (void)setExpanded:(BOOL)expanded
{
    self.expandedImageView.transform = CGAffineTransformIdentity;
    CGFloat angle = expanded ? M_PI/2 : -M_PI/2;
    self.expandedImageView.transform = CGAffineTransformMakeRotation(angle);
    _expanded = expanded;

}

- (void)expandedAnimated:(BOOL)expanded
{
   if(_expanded == expanded)
       return;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        CGFloat angle = expanded ? M_PI_2 : -M_PI_2;
        self.expandedImageView.transform = CGAffineTransformRotate(self.expandedImageView.transform, angle);

    }];
    _expanded = expanded;

}

- (void)updateUI:(VSTreeViewCellModel *)model
{
    self.nameLabel.text = model.name;
    self.level = model.level;
    self.expandedImageView.hidden = !model.expandedShow;
    [self setExpanded:model.expanded];
    [self setNeedsLayout];

}

@end
